package com.itheima.a03dom4jdemo;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class dom4jDemo1 {
    public static void main(String[] args) throws DocumentException {
        ArrayList<Person> list = new ArrayList<>();

        //1.创建解析器对象
        SAXReader saxReader = new SAXReader();
        //2.利用解析器去解析xml文件，并返回文档对象
        File file = new File("sockethomework\\src\\com\\itheima\\a03dom4jdemo\\person.xml");
        Document document = saxReader.read(file);

        //3.下面一层一层的扒开获取里面的数据即可
        //自己解析的时候一定要一层一层的解析
        //获取到根标签
        Element rootElement = document.getRootElement();

        //4.获取根标签的子标签
        List<Element> persons = rootElement.elements("person");

        for (Element person : persons) {
            //5.继续获取里面的内容

            //属性id
            Attribute id = person.attribute("id");
            String idvalue = id.getText();

            //姓名name
            Element name = person.element("name");
            String namevalue = name.getText();

            //年龄age
            Element age = person.element("age");
            String agevalue = age.getText();
            int ageInt = Integer.parseInt(agevalue);

            //创建对象
            Person p = new Person(idvalue, namevalue, ageInt);
            list.add(p);
        }

        //打印集合
        //System.out.println(list);

        //用stream流打印IO流
        list.stream().forEach(s -> System.out.println(s));
    }
}
